package com.wootion.cims.module.systemsetting.polt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wootion.cims.dao.*;
import com.wootion.cims.general.utils.GetIp;
import com.wootion.cims.module.communitymerchant.model.Shop;
import com.wootion.cims.module.communityresidence.residencelist.model.Residence;
import com.wootion.cims.module.systemsetting.log.model.SysLog;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import com.wootion.cims.module.systemsetting.polt.service.SysPlotService;
import com.wootion.cims.module.systemsetting.community.model.SysCommunity;
import com.wootion.cims.module.systemsetting.polt.dto.SysPlotDto;
import com.wootion.cims.module.systemsetting.role.model.SysRole;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author: LanQiang
 * @Date: 2022/11/21/11:26
 * @Description: 作用xxx
 */
@Service
@Slf4j
public class SysPlotServiceImpl implements SysPlotService {

    @Resource
    private SysPlotDao sysPlotDao;

    @Resource
    private SysCommunityDao sysCommunityDao;

    @Resource
    private SysRoleDao sysRoleDao;

    @Resource
    private UserDao userDao;

    @Resource
    private ResidenceDao residenceDao;

    @Resource
    private ShopDao shopDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Resource
    private SysUserCommunityDao sysUserCommunityDao;

    @Resource
    private SysLogDao sysLogDao;

    /**
     * 查询所有小区信息/或按照条件查询,并分页返回
     *
     * @param condition
     * @param limit
     * @param page
     * @return
     */
    @Override
    public ResponseResult list(String condition, Integer page, Integer limit) {
        //获取当前登陆用户所能查看的所有社区下的所有小区
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId,user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        if ("street:admin".equals(roleKey)) {
            PageDTO<SysPlotDto> dtoPage = new PageDTO<>(page,limit);
            PageDTO<SysPlotDto> pageDto = sysPlotDao.findPageDto(dtoPage, condition, null);
            return ResponseResult.builder().data(pageDto).build();
        }
        List<SysPlot> sysPlots = sysPlotDao.findUserIdBySysPlot(user.getId());
        Set<String> sysPlotIds = new HashSet<>();
        for (SysPlot sysPlot : sysPlots) {
            sysPlotIds.add(sysPlot.getId());
        }
        List<String> ids = new ArrayList<>(sysPlotIds);
        PageDTO<SysPlotDto> dtoPage = new PageDTO<>(page, limit);
        PageDTO<SysPlotDto> pageDto = sysPlotDao.findPageDto(dtoPage, condition, ids);
        return ResponseResult.builder().data(pageDto).build();
    }

    /**
     * 添加/修改时，查询小区所属的社区分组
     *
     * @return
     */
    @Override
    public ResponseResult groupPlot() {
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(wrapper);
        SysRole role = sysRoleDao.findRole(sysUserRole.getRoleId());
        if (Objects.isNull(role)) {
            return ResponseResult.builder().build();
        }
        if ("street:admin".equals(role.getRoleKey())) {
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysCommunity::getEnable,true);
            lambdaQueryWrapper.groupBy(SysCommunity::getId);
            List<SysCommunity> communities = sysCommunityDao.selectList(lambdaQueryWrapper);
            return ResponseResult.builder().data(communities).build();
        }
        //先根据用户id查询所有对应的社区id
        List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
        //在根据社区id来进行分组
        if (Objects.isNull(commnityIds) || commnityIds.size() <= 0) {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户还没有任何社区权限").build();
        }
        List<SysCommunity> communityList = sysCommunityDao.findByCommunityIds(commnityIds);
        return ResponseResult.builder().data(communityList).build();
    }

    /**
     * 添加小区
     *
     * @param sysPlotDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult save(SysPlotDto sysPlotDto) {
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        String name = sysPlotDto.getName();
        String newName = name.replace(" ", "");
        sysPlotDto.setName(newName);
        //如果有id，代表修改
        if (StringUtils.hasText(sysPlotDto.getId())) {
            LambdaQueryWrapper<SysPlot> plotLambdaQueryWrapper = new LambdaQueryWrapper<>();
            plotLambdaQueryWrapper.eq(SysPlot::getId,sysPlotDto.getId());
            SysPlot sysPlot1 = sysPlotDao.selectOne(plotLambdaQueryWrapper);

            LambdaQueryWrapper<SysPlot> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(SysPlot::getName,sysPlotDto.getName());
            SysPlot sysPlot2 = sysPlotDao.selectOne(wrapper2);

            if(Objects.isNull(sysPlot2) || sysPlot1.getId().equals(sysPlot2.getId())){
                LambdaQueryWrapper<SysCommunity> wrapper5 = new LambdaQueryWrapper<>();
                wrapper5.eq(SysCommunity::getName,sysPlotDto.getSysCommunity().getName());
                SysCommunity sysCommunity = sysCommunityDao.selectOne(wrapper5);
                SysPlot sysPlot = new SysPlot();
                BeanUtils.copyProperties(sysPlotDto, sysPlot);
                sysPlot.setEnabled(true);
                sysPlot.setUpdateTime(new Date());
                sysPlot.setUpdateUserid(user.getId());
                sysPlot.setCommunityId(sysCommunity.getId());
                LambdaQueryWrapper<SysPlot> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(SysPlot::getId,sysPlot.getId());
                int rows = sysPlotDao.update(sysPlot,queryWrapper3);
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            LambdaQueryWrapper<SysPlot> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
            wrapper.eq(SysPlot::getEnabled,true);
            //修改之后的小区名称也不能重复
            if (sysPlotDao.exists(wrapper)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称正在被使用，请跟换名称后再添加！").build();
            }
            LambdaQueryWrapper<SysPlot> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
            wrapper4.eq(SysPlot::getEnabled,false);
            if (sysPlotDao.exists(wrapper4)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称已删除，请使用其他名称或联系统管理员处理").build();
            }
        }
        //如果没有id代表新增小区
        LambdaQueryWrapper<SysPlot> queryWrapperwrapper = new LambdaQueryWrapper<>();
        queryWrapperwrapper.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
        queryWrapperwrapper.eq(SysPlot::getEnabled,true);
        //小区名称不能重复
        if (sysPlotDao.exists(queryWrapperwrapper)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称正在被使用，请跟换名称后再添加！").build();
        }
        LambdaQueryWrapper<SysPlot> queryWrapperwrapper2 = new LambdaQueryWrapper<>();
        queryWrapperwrapper2.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
        queryWrapperwrapper2.eq(SysPlot::getEnabled,false);
        //小区名称不能重复
        if (sysPlotDao.exists(queryWrapperwrapper2)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称已删除，请使用其他名称或联系统管理员处理").build();
        }
        SysCommunity sysCommunity = sysPlotDto.getSysCommunity();
        LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
        SysCommunity sysCommunity1 = sysCommunityDao.selectOne(lambdaQueryWrapper);
        SysPlot sysPlot = new SysPlot();
        BeanUtils.copyProperties(sysPlotDto, sysPlot);
        sysPlot.setCommunityId(sysCommunity1.getId());
        sysPlot.setEnabled(true);
        sysPlot.setCreateTime(new Date());
        sysPlot.setCreateUserid(user.getId());
        int rows = sysPlotDao.insert(sysPlot);
        return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }
    /**
     * 修改小区
     *
     * @param sysPlotDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult update(SysPlotDto sysPlotDto, HttpServletRequest request) {
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        String name = sysPlotDto.getName();
        String newName = name.replace(" ", "");
        sysPlotDto.setName(newName);
        //如果有id，代表修改
        if (StringUtils.hasText(sysPlotDto.getId())) {
            LambdaQueryWrapper<SysPlot> plotLambdaQueryWrapper = new LambdaQueryWrapper<>();
            plotLambdaQueryWrapper.eq(SysPlot::getId,sysPlotDto.getId());
            SysPlot sysPlot1 = sysPlotDao.selectOne(plotLambdaQueryWrapper);

            LambdaQueryWrapper<SysPlot> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(SysPlot::getName,sysPlotDto.getName());
            SysPlot sysPlot2 = sysPlotDao.selectOne(wrapper2);

            if(Objects.isNull(sysPlot2) || sysPlot1.getId().equals(sysPlot2.getId())){
                LambdaQueryWrapper<SysCommunity> wrapper5 = new LambdaQueryWrapper<>();
                wrapper5.eq(SysCommunity::getName,sysPlotDto.getSysCommunity().getName());
                SysCommunity sysCommunity = sysCommunityDao.selectOne(wrapper5);
                SysPlot sysPlot = new SysPlot();
                BeanUtils.copyProperties(sysPlotDto, sysPlot);
                sysPlot.setEnabled(true);
                sysPlot.setUpdateTime(new Date());
                sysPlot.setUpdateUserid(user.getId());
                sysPlot.setCommunityId(sysCommunity.getId());
                LambdaQueryWrapper<SysPlot> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(SysPlot::getId,sysPlot.getId());
                int rows = sysPlotDao.update(sysPlot,queryWrapper3);
                SysLog sysLog = new SysLog();
                sysLog.setIncident("小区信息");
                sysLog.setType("修改");
                sysLog.setValue("系统日志");
                sysLog.setCreateTime(new Date());
                sysLog.setIp(GetIp.getIpAddr(request));
                User user2 = (User) ShiroUtils.getSubject().getPrincipal();
                sysLog.setOperator(user2.getUsername());
                sysLog.setContent("小区名称:"+sysPlot1.getName());
               if(rows > 0){
                 sysLog.setResult("成功");
                 StringBuilder stringBuilder = new StringBuilder();
                   if(!sysCommunity.getName().equals(sysPlotDto.getSysCommunity().getName())){
                       stringBuilder.append("所属社区被修改，修改前:").append(sysCommunity.getName()).append(",修改后:").append(sysPlotDto.getSysCommunity().getName()).append("。");
                   }
                   if(!sysPlot1.getName().equals(sysPlotDto.getName())){
                       stringBuilder.append("小区名称被修改，修改前:").append(sysPlot1.getName()).append(",修改后:").append(sysPlotDto.getName()).append("。");
                   }
                   if(!sysPlot1.getArea().equals(sysPlotDto.getArea())){
                       stringBuilder.append("小区面积被修改，修改前:").append(sysPlot1.getArea()).append(",修改后:").append(sysPlotDto.getArea()).append("。");
                   }
                   if(!sysPlot1.getAddress().equals(sysPlotDto.getAddress())){
                       stringBuilder.append("小区地址被修改，修改前:").append(sysPlot1.getAddress()).append(",修改后:").append(sysPlotDto.getAddress()).append("。");
                   }
                   sysLog.setDetails(stringBuilder.toString());
               }else{
                   sysLog.setResult("失败");
               }
                int insert = sysLogDao.insert(sysLog);
                if (insert > 0) {
                    log.info("日志记录成功");
                } else {
                    log.error("日志记录失败");
                }
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            LambdaQueryWrapper<SysPlot> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
            wrapper.eq(SysPlot::getEnabled,true);
            //修改之后的小区名称也不能重复
            if (sysPlotDao.exists(wrapper)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称正在被使用，请跟换名称后再添加！").build();
            }
            LambdaQueryWrapper<SysPlot> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
            wrapper4.eq(SysPlot::getEnabled,false);
            if (sysPlotDao.exists(wrapper4)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称已删除，请使用其他名称或联系统管理员处理").build();
            }
        }
        //如果没有id代表新增小区
        LambdaQueryWrapper<SysPlot> queryWrapperwrapper = new LambdaQueryWrapper<>();
        queryWrapperwrapper.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
        queryWrapperwrapper.eq(SysPlot::getEnabled,true);
        //小区名称不能重复
        if (sysPlotDao.exists(queryWrapperwrapper)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称正在被使用，请跟换名称后再添加！").build();
        }
        LambdaQueryWrapper<SysPlot> queryWrapperwrapper2 = new LambdaQueryWrapper<>();
        queryWrapperwrapper2.eq(StringUtils.hasText(sysPlotDto.getName()), SysPlot::getName, sysPlotDto.getName());
        queryWrapperwrapper2.eq(SysPlot::getEnabled,false);
        //小区名称不能重复
        if (sysPlotDao.exists(queryWrapperwrapper2)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message("小区名称已删除，请使用其他名称或联系统管理员处理").build();
        }
        SysCommunity sysCommunity = sysPlotDto.getSysCommunity();
        LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
        SysCommunity sysCommunity1 = sysCommunityDao.selectOne(lambdaQueryWrapper);
        SysPlot sysPlot = new SysPlot();
        BeanUtils.copyProperties(sysPlotDto, sysPlot);
        sysPlot.setCommunityId(sysCommunity1.getId());
        sysPlot.setEnabled(true);
        sysPlot.setCreateTime(new Date());
        sysPlot.setCreateUserid(user.getId());
        int rows = sysPlotDao.insert(sysPlot);
        return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }
    /**
     * 删除小区
     *
     * @param sysPlotDto
     * @return
     */
    @Override
    public ResponseResult deletePlot(SysPlotDto sysPlotDto) {
        if (StringUtils.hasText(sysPlotDto.getId())) {
            //当前小区下，住宅数量为0，商户数量为0的时候，可以删除
            LambdaQueryWrapper<Residence> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Residence::getEnabled,true);
            queryWrapper1.eq(Residence::getPlotId,sysPlotDto.getId());
            List<Residence> residenceList = residenceDao.selectList(queryWrapper1);
            if(residenceList.size()>0){
                return ResponseResult.builder().message("当前小区下，关联的有住宅不能删除").code(ResultCode.SYSTEM_ERROR.getCode()).build();
            }
            LambdaQueryWrapper<Shop> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Shop::getPlotId,sysPlotDto.getId());
            queryWrapper2.eq(Shop::getEnabled,true);
            List<Shop> shops = shopDao.selectList(queryWrapper2);
            if(shops.size()>0){
                return ResponseResult.builder().message("当前小区下，关联的有商户不能删除").code(ResultCode.SYSTEM_ERROR.getCode()).build();
            }

            SysPlot sysPlot = new SysPlot();
            BeanUtils.copyProperties(sysPlotDto, sysPlot);
            sysPlot.setEnabled(false);
            int rows = sysPlotDao.updateById(sysPlot);
            return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
        return ResponseResult.builder().code(ResultCode.PARAM_IS_BLANK.getCode()).message(ResultCode.PARAM_IS_BLANK.getMessage()).build();
    }
}
